<template>
  <div class="dashboard-container">
    <div class="app-container">
      <el-card class="tree-card">
        <TreeTools :tree-node="company" :is-root="true" @addPepts="addPepts" />
        <hr>
        <el-tree
          default-expand-all
          :data="departs"
          :props="defaultProps"
          default-expand
        >
          <!-- 此处进行封装 -->
          <TreeTools slot-scope="{ data }" :tree-node="data" @editDepts="editDepts" @addPepts="addPepts" @delDepts="getDepartments" />
        </el-tree>
      </el-card>
      <AddDept ref="addDept" :show-dialog.sync="showDialog" :node="node" @addDepts="getDepartments" />
    </div>
  </div>
</template>

<script>
import TreeTools from './components/tree-tools'
import AddDept from './components/add-dept'
import { getDepartments } from '@/api/departments'
import { tranListToTreeData } from '@/utils'
export default {
  components: {
    TreeTools,
    AddDept
  },
  data() {
    return {
      departs: [],
      defaultProps: {
        label: 'name',
        children: 'children'
      },
      company: {
        name: '江苏传智教育科技股份有限公司',
        children: '负责人',
        id: ''
      },
      showDialog: false,
      node: {}
    }
  },
  created() {
    this.getDepartments()
  },
  methods: {
    async getDepartments() {
      const res = await getDepartments()
      this.departs = tranListToTreeData(res.depts, '')
      console.log('------', res)
    },
    addPepts(treeNode) {
      console.log('子组件', treeNode)
      // 控制弹窗
      this.showDialog = true
      this.node = treeNode
      // 获取的treeNode 传给弹窗
    },
    async editDepts(treeNode) {
      // 控制弹窗
      this.showDialog = true
      this.node = treeNode
      await this.$refs.addDept.getDepartDetail(treeNode.id)
    }
  // 以下步骤已封装在uyils/index.js中,引入即可
  // tranListToTreeData(list, pid) {
  //   const res = []
  //   list.forEach((item) => {
  //     if (item.pid === pid) {
  //       // 多了递归部分
  //       const children = this.tranListToTreeData(list, item.id)
  //       if (children.length) {
  //         item.children = children
  //       }
  //       // 原本没找到递归时, 放在数组中即可
  //       res.push(item)
  //     }
  //   })
  //   return res
  // }
  }
}
</script>

<style scoped>
.tree-card {
  padding: 30px 140px;
  font-size: 14px;
}
</style>
